<template>
  <div>
    <van-nav-bar title="搜索中心" left-arrow @click-left="$router.back()" />
    <!-- 导入search组件添加搜索功能（回车搜索和点击搜索按钮搜索） -->
    <van-search
      v-model="value"
      show-action
      placeholder="请输入搜索关键词"
      @search="onSearch"
      @input="onInput"
    >
      <!-- 使用插槽添加搜索按钮 （单标签要改成双标签） -->
      <template #action>
        <div @click="onSearch">搜索</div>
      </template>
    </van-search>
    <!-- 加上搜索结果 -->
    <van-cell-group>
      <van-cell
        v-for="(item, index) in showList"
        :key="index"
        icon="search"
        @click="
          $router.push({ paht: '/searchResult', query: { q: list[index] } })
        "
      >
        <template #title>
          <div v-html="item"></div>
        </template>
      </van-cell>
    </van-cell-group>
    <!-- 4.历史记录 -->
    <van-cell-group>
      <van-cell title="历史记录" />
      <van-cell title="javascript">
        <template #right-icon>
          <van-icon name="search" class="search-icon" />
        </template>
      </van-cell>
      <van-cell title="javascript">
        <template #right-icon>
          <van-icon name="search" class="search-icon" />
        </template>
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script>
import { getSuggestionList } from './home.js'
export default {
  name: 'search',
  data () {
    return {
      value: '',
      list: [],
      timeId: null
    }
  },
  methods: {
    onSearch () {
      this.$router.push({
        path: '/searchResult',
        query: {
          q: this.value
        }
      })
    },
    onInput () {
      clearTimeout(this.timeId)
      this.timeId = setTimeout(async () => {
        if (this.value.length == 0) {
          this.list = []
          return
        }
        let res = await getSuggestionList(this.value)
        console.log(res)
        this.list = res.data.data.options
      }, 500)
    }
  },
  computed: {
    showList () {
      return this.list.map(item => {
        let regexp = new RegExp(this.value, 'ig')
        return item.replace(
          regexp,
          match => `<span style="color:red">${match}</span>`
        )
      })
    }
  }
}
</script>

<style></style>
